package com.net.framework.help.recorder;

import android.media.MediaRecorder;

import com.net.framework.help.application.BaseApplication;
import com.net.framework.help.utils.DateUtil;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class AudioManage {
    private MediaRecorder mMediaRecorder;  //MediaRecorder可以实现录音和录像。需要严格遵守API说明中的函数调用先后顺序.
    private String mCurrentFilePath;
    private static AudioManage mInstance;

    private boolean isPrepared; // 标识MediaRecorder准备完毕

    private AudioManage() {
    }

    /**
     * 回调“准备完毕”
     *
     * @author songshi
     */
    public interface AudioStateListenter {
        void wellPrepared();    // prepared完毕
    }

    public AudioStateListenter mListenter;

    public void setOnAudioStateListenter(AudioStateListenter audioStateListenter) {
        mListenter = audioStateListenter;
    }

    /**
     * 使用单例实现 AudioManage
     *
     * @return
     */
    //DialogManage主要管理Dialog，Dialog主要依赖Context，而且此Context必须是Activity的Context，
    //如果DialogManage写成单例实现，将是Application级别的，将无法释放，容易造成内存泄露，甚至导致错误
    public static AudioManage getInstance() {
        if (mInstance == null) {
            synchronized (AudioManage.class) {   // 同步
                if (mInstance == null) {
                    mInstance = new AudioManage();
                }
            }
        }
        return mInstance;
    }

    /**
     * 准备录音
     */
    public void prepareAudio() {
        try {
            isPrepared = false;
            mCurrentFilePath = BaseApplication.getApplication().getExternalCacheDir() + File.separator + createAudioName();
            //MediaRecorder可以实现录音和录像。需要严格遵守API说明中的函数调用先后顺序.
            mMediaRecorder = new MediaRecorder();
            mMediaRecorder.setOutputFile(mCurrentFilePath);    // 设置输出文件
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);    // 设置MediaRecorder的音频源为麦克风
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);    // 设置音频的格式
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);    // 设置音频的编码为AMR_NB
//            //配置mMediaRecorder相应参数
//            //从麦克风采集声音数据
//            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//            //设置保存文件格式为MP4
//            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
//            //设置采样频率,44100是所有安卓设备都支持的频率,频率越高，音质越好，当然文件越大
//            mMediaRecorder.setAudioSamplingRate(44100);
//            //设置声音数据编码格式,音频通用格式是AAC
//            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
//            //设置编码频率
//            mMediaRecorder.setAudioEncodingBitRate(96000);
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            isPrepared = true; // 准备结束
            if (mListenter != null) {
                mListenter.wellPrepared();
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获得音量等级
     * maxLevel最大为7；
     * mMediaRecorder.getMaxAmplitude() / 32768：0——1；
     *
     * @return
     */
    public float getVoiceLevel() {
        if (isPrepared) {
            try {
                //mMediaRecorder.getMaxAmplitude()——获得最大振幅:1-32767
                return mMediaRecorder.getMaxAmplitude() * 1.0f / 32768;
            } catch (Exception e) {
            }
        }
        return 0;
    }

    /**
     * 释放资源
     */
    public void release() {
        if (null != mMediaRecorder) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }

    /**
     * 取消（释放资源+删除文件）
     */
    public void cancel() {
        release();
        if (mCurrentFilePath != null) {
            File file = new File(mCurrentFilePath);
            file.delete();    //删除录音文件
            mCurrentFilePath = null;
        }
    }

    public String getCurrentFilePath() {
        // TODO Auto-generated method stub
        return mCurrentFilePath;
    }

    public String createAudioName() {
//        long time = System.currentTimeMillis();
        String fileName = "voice-android" + DateUtil.getFormatDateTime(new Date(), "yyyyMMddHHmmss") + ".amr";
//        String fileName = UUID.randomUUID().toString() + time + ".mp3";
        return fileName;
    }
}

